package resource

import (
	"github.com/google/uuid"
	"gorm.io/gorm"
	"mallgo/internal/common/response"
	"mallgo/internal/resources/user/api/domain/request"
	response2 "mallgo/internal/resources/user/api/domain/response"
	userModel "mallgo/internal/resources/user/model"
	"mallgo/utils"
	"strings"
	"time"
)

type UserResource struct {
	db *gorm.DB
}

func NewUserResource(db *gorm.DB) *UserResource {
	return &UserResource{db}
}

func (h *UserResource) Register(req *request.RegisterRequest) *response.ResponseObject {

	// 检查用户名是否已经存在
	var existingUser userModel.UserAccount

	if err := h.db.Where("username = ?", req.Username).First(&existingUser).Error; err == nil {
		return response.Error(500, "该用户名已经存在")
	}

	// 创建用户账户
	userAccount := userModel.UserAccount{
		Username: req.Username,
		AddDate:  time.Now(),
	}

	// 创建密码，假设没有加盐处理（可以根据需求进行加密）
	userPassword := userModel.UserPassword{
		Password: req.Password, // 这里应该加盐并加密
		AddDate:  time.Now(),
	}

	// 创建用户信息
	userInfo := userModel.UserInfo{
		Name:      req.Username,
		Phone:     req.Phone,
		AddDate:   time.Now(),
		BeginDate: time.Now(),
		LastDate:  time.Now(),
	}

	// 启动事务
	tx := h.db.Begin()
	if err := tx.Create(&userInfo).Error; err != nil {
		tx.Rollback()
		return response.Error(500, "创建用户失败")
	}
	userPassword.UserID = userInfo.ID
	userPassword.AddDate = time.Now()
	userPassword.LastDate = time.Now()
	password, salt, _ := utils.Password(req.Password)
	userPassword.Password = password
	userPassword.Salt = salt
	if err := tx.Create(&userPassword).Error; err != nil {
		tx.Rollback()
		return response.Error(500, "创建密码失败")

	}
	userAccount.UserID = userInfo.ID
	userAccount.AddDate = time.Now()

	lastDate := time.Now()
	userAccount.LastDate = &lastDate
	if err := tx.Create(&userAccount).Error; err != nil {
		tx.Rollback()
		return response.Error(500, "创建用户账号失败")
	}

	// 提交事务
	tx.Commit()
	// 注册成功
	return response.Success(userInfo)
}

func (h *UserResource) Login(req *request.LoginRequest) *response.ResponseData[response2.UserResponse] {

	// 检查用户名是否存在
	var userAccount userModel.UserAccount
	if err := h.db.Where("username = ?", req.Username).First(&userAccount).Error; err != nil {
		return response.ErrorData[response2.UserResponse](501, "用户名不存在")
	}

	// 检查密码是否正确
	var userPassword userModel.UserPassword
	if err := h.db.Where("user_id = ?", userAccount.UserID).First(&userPassword).Error; err != nil {
		return response.ErrorData[response2.UserResponse](502, "该用户没有设置密码")
	}

	password := utils.HashPassword(req.Password, userPassword.Salt, 2048)
	if !strings.EqualFold(password, userPassword.Password) {
		return response.ErrorData[response2.UserResponse](503, "密码错误")
	}

	// 密码正确，返回用户信息
	var userInfo userModel.UserInfo
	if err := h.db.Where("id = ?", userAccount.UserID).First(&userInfo).Error; err != nil {
		return response.ErrorData[response2.UserResponse](504, "用户信息获取失败")
	}
	id, _ := uuid.NewUUID()
	idStr := id.String()
	res := response2.UserResponse{
		Id:        userInfo.ID,
		SessionId: idStr,
		Name:      userInfo.Name,
		Avatar:    userInfo.Avatar,
	}
	return response.SuccessData(res)
}
